package com.aitou.mrylive.presentation.ui.main.index;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.aitou.mrylive.BeautyLiveApplication;
import com.aitou.mrylive.R;
import com.aitou.mrylive.data.bean.HotAnchorSummary;
import com.aitou.mrylive.data.bean.Banner;
import com.aitou.mrylive.data.bean.UpDataBean;
import com.aitou.mrylive.data.repository.SourceFactory;
import com.aitou.mrylive.domain.LocalDataManager;
import com.aitou.mrylive.presentation.ui.base.BaseFragment;
import com.aitou.mrylive.presentation.ui.base.ptr.BasePtr;
import com.aitou.mrylive.presentation.ui.base.recycler.SimpleRecyclerHolder;
import com.aitou.mrylive.presentation.ui.login.LoginSelectActivity;
import com.aitou.mrylive.presentation.ui.main.MainActivity;
import com.aitou.mrylive.presentation.ui.main.webview.SimpleWebViewActivity;
import com.aitou.mrylive.presentation.ui.room.RoomActivity;
import com.aitou.mrylive.presentation.ui.room.player.PlayerFragment;
import com.aitou.mrylive.presentation.ui.widget.MessageDialog;
import com.aitou.mrylive.util.Const;
import com.aitou.mrylive.util.DownLoadUtil;
import com.aitou.mrylive.util.L;
import com.aitou.mrylive.util.Packages;
import com.aitou.mrylive.util.Spans;
import com.aitou.mrylive.util.upapk.DownLoadService;
import com.umeng.analytics.MobclickAgent;
import com.yolanda.nohttp.Headers;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.OnResponseListener;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

/**
 * @author Muyangmin
 * @since 1.0.0
 */
public class HotAnchorFragment extends BaseFragment implements HotAnchorInterface {

    private static final long AUTO_REFRESH_TIME = 90;

    private PtrFrameLayout ptrFrameLayout;
    private RecyclerView recyclerView;
    private HotAnchorPresenter presenter;
    private HotAnchorAdapter adapter;
    private ScheduledExecutorService autoRefreshService;
//    地区标题
    private String city;
//    性别
    private String sex;
    public static HotAnchorFragment newInstance() {
        return new HotAnchorFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.frag_hot_anchor_list;
    }

    @Override
    protected void initViews(View view) {
        city="热门";
//        版本更新
        upData();
        presenter = new HotAnchorPresenter(this);
        ptrFrameLayout = $(view, R.id.hot_anchor_ptr);
        ptrFrameLayout.disableWhenHorizontalMove(true);
        //设置为不可上拉加载的样式，只需要禁用掉上拉Feature即可，不需要改动逻辑代码。
//        BasePtr.setPagedPtrStyle(ptrFrameLayout);
        BasePtr.setRefreshOnlyStyle(ptrFrameLayout);
        recyclerView = $(view, R.id.hot_anchor_recycler);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        ptrFrameLayout.setPtrHandler(new PtrDefaultHandler2() {

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return super.checkCanDoRefresh(frame, recyclerView, header);
            }

            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                return super.checkCanDoLoadMore(frame, recyclerView, footer);
            }

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
//                加载第二章
                presenter.loadNextPage();
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
//                加载啊第一张
                presenter.loadFirstPage(LocalDataManager.getInstance().getLoginInfo().getToken(),city,sex);
            }
        });
        ptrFrameLayout.autoRefresh();
    }

    @Override
    public void onResume() {
        super.onResume();
        //自动刷新服务
        autoRefreshService = Executors.newSingleThreadScheduledExecutor();
        autoRefreshService.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                L.d(LOG_TAG, "Auto refreshing hot anchor list...");
                if (presenter!=null){
                    presenter.loadFirstPage(LocalDataManager.getInstance().getLoginInfo().getToken(),"热门","");
                }
            }
        }, AUTO_REFRESH_TIME, AUTO_REFRESH_TIME, TimeUnit.SECONDS);
    }

    @Override
    public void onPause() {
//        MobclickAgent.onPageStart("主页-热门");
        super.onPause();
        autoRefreshService.shutdownNow();
        L.i(LOG_TAG, "Auto refreshing service has been shutdown.");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        presenter.unsubscribeTasks();
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public void showLoadingComplete() {
        ptrFrameLayout.refreshComplete();
    }

//    banners
    @Override
    public void displayBanners(List<Banner> banners) {
        if (adapter == null) {
            adapter = new HotAnchorAdapter(new ArrayList<HotAnchorSummary>());
            recyclerView.setAdapter(adapter);
        }
        adapter.setBannerList(banners);
    }

    @Override
    public void showData(List<HotAnchorSummary> list) {
        for (int i=0;i<list.size();i++){
            Log.i("mrl",list.get(i).toString());
        }
        if (adapter == null) {
            adapter = new HotAnchorAdapter(list);
            recyclerView.setAdapter(adapter);
        } else {
            adapter.setDataList(list);
        }
    }

    @Override
    public void appendData(List<HotAnchorSummary> list) {
        adapter.appendData(list);
    }

    private class BannerHolder implements Holder<Banner> {

        private SimpleDraweeView drawee;

        @Override
        public View createView(Context context) {
            drawee = new SimpleDraweeView(context);
            drawee.setScaleType(ImageView.ScaleType.FIT_XY);
            return drawee;
        }

        @Override
        public void UpdateUI(Context context, int position, Banner data) {
            if (TextUtils.isEmpty(data.getImageUrl())) {
                drawee.setImageURI(Uri.EMPTY);
            } else {
                drawee.setImageURI(SourceFactory.wrapPathToUri(data.getImageUrl()));
            }
        }
    }

    private class HotAnchorAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private static final int TYPE_HEADER = 1;
        private static final int TYPE_CONTENT = 2;

        private List<HotAnchorSummary> dataList;
        private List<Banner> bannerList;

        public HotAnchorAdapter(List<HotAnchorSummary> dataList) {
            this.dataList = dataList;
        }

        public final void setDataList(List<HotAnchorSummary> dataList) {
            this.dataList = dataList;
            notifyDataSetChanged();
        }

        public final void appendData(List<HotAnchorSummary> appends) {
            this.dataList.addAll(appends);
            notifyDataSetChanged();
        }

        public void setBannerList(List<Banner> bannerList) {
            this.bannerList = bannerList;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            View view;
            if (viewType == TYPE_CONTENT) {
                view = inflater.inflate(R.layout.item_hot_anchor, parent, false);
                return new HotAnchorHolder(view);
            } else {
                view = inflater.inflate(R.layout.header_hot_anchor, parent, false);
                return new HotAnchorHeaderHolder(view);
            }
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (getItemViewType(position) == TYPE_CONTENT) {
                ((HotAnchorHolder) holder).displayData(dataList.get(position - 1));
            } else {
                ((HotAnchorHeaderHolder) holder).displayBanner(bannerList);
            }
        }

        @Override
        public int getItemViewType(int position) {
            if (position == 0) {
                return TYPE_HEADER;
            }
            return TYPE_CONTENT;
        }

        @Override
        public int getItemCount() {
            return dataList.size() + 1;
        }
    }

    private class HotAnchorHeaderHolder extends RecyclerView.ViewHolder {

        private ConvenientBanner<Banner> cvBanner;

        public HotAnchorHeaderHolder(View itemView) {
            super(itemView);
            cvBanner = $(itemView, R.id.hot_anchor_banner);
        }

        public void displayBanner(final List<Banner> banners) {
            cvBanner.setPages(new CBViewHolderCreator() {
                @Override
                public Object createHolder() {
                    cvBanner.startTurning(5000);
                    cvBanner.setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(int position) {
//                            banana显示网页
                            Log.i("mrl",banners.get(position).getTargetUrl()+"显示网页咯");
                            startActivity(SimpleWebViewActivity.createIntent(getActivity(),
                                    SourceFactory.wrapPath(banners.get(position).getTargetUrl())));
                        }
                    });
                    return new BannerHolder();
                }
            }, banners)
                    .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R
                            .drawable.ic_page_indicator_focused})
                    .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                    .setManualPageable(true)
            ;
        }

    }

    private class HotAnchorHolder extends SimpleRecyclerHolder<HotAnchorSummary> {

        private SimpleDraweeView drawSnap;
        private TextView tvNickname;
        private TextView tvLocation;
        private TextView tvOnlineCount;
        private TextView note;
        private SimpleDraweeView drawAvatar;
        private TextView tvTitle;
        private TextView tvTopic;
        @SuppressWarnings("unused")
        public HotAnchorHolder(View itemView) {
            super(itemView);
            drawAvatar = (SimpleDraweeView) itemView.findViewById(R.id.img_user_avatar);
            drawSnap = (SimpleDraweeView) itemView.findViewById(R.id
                    .item_hot_anchor_img_front_cover);
            tvNickname = (TextView) itemView.findViewById(R.id.item_hot_anchor_tv_nickname);
            tvLocation = (TextView) itemView.findViewById(R.id.item_hot_anchor_tv_location);
            tvOnlineCount = (TextView) itemView.findViewById(R.id.item_hot_anchor_tv_online_count);
            tvTitle= (TextView) itemView.findViewById(R.id.item_hot_anchor_title);
            tvTopic= (TextView) itemView.findViewById(R.id.item_hot_anchor_topic);
        }

        @Override
        public void displayData(final HotAnchorSummary data) {
            if (data.getRoomTitle()==null){
                tvTitle.setVisibility(View.GONE);
            }else{
                tvTitle.setVisibility(View.VISIBLE);
                tvTitle.setText(data.getRoomTitle());
            }
            if (data.getTopic()==null){
                tvTopic.setVisibility(View.GONE);
            }else {
                tvTopic.setVisibility(View.VISIBLE);
                StringBuffer stringBuffer = new StringBuffer();
                for (int i=0;i<data.getTopic().size();i++){
                    stringBuffer.append("#"+data.getTopic().get(i).getTitle()+"#");
                }
                tvTopic.setText(stringBuffer.toString());
            }
            drawAvatar.setImageURI(SourceFactory.wrapPathToUri(data.getAvatar()));
            drawSnap.setImageURI(SourceFactory.wrapPathToUri(data.getSnap()));
            tvNickname.setText(data.getNickname());
            tvLocation.setText(data.getCity());
            tvOnlineCount.setText(Spans.createSpan("", String.valueOf(data.getOnlineCount()),"", new
                            ForegroundColorSpan
                            (ContextCompat.getColor(getContext(), R.color.yunkacolor)),
                    new RelativeSizeSpan(1.6F)));
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(RoomActivity.createIntent(getActivity(),
                            RoomActivity.TYPE_VIEW_LIVE,
                            data.getCurrentRoomNum(),
                            data.getId(),
                            PlayerFragment.createArgs(data)));
                    getActivity().overridePendingTransition(R.anim.fragment_slide_left_in, R.anim
                            .fragment_slide_left_out);
                }
            });
            //TODO note
        }
    }



    public static boolean checkPermission(Context context, String permission) {
        boolean result = false;
        if (Build.VERSION.SDK_INT >= 23) {
            try {
                Class clazz = Class.forName("android.content.Context");
                Method method = clazz.getMethod("checkSelfPermission", String.class);
                int rest = (Integer) method.invoke(context, permission);
                if (rest == PackageManager.PERMISSION_GRANTED) {
                    result = true;
                } else {
                    result = false;
                }
            } catch (Exception e) {
                result = false;
            }
        } else {
            PackageManager pm = context.getPackageManager();
            if (pm.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
                result = true;
            }
        }
        return result;
    }
    public static String getDeviceInfo(Context context) {
        try {
            org.json.JSONObject json = new org.json.JSONObject();
            android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String device_id = null;

            if (checkPermission(context, Manifest.permission.READ_PHONE_STATE)) {
                device_id = tm.getDeviceId();
            }
            String mac = null;
            FileReader fstream = null;
            try {
                fstream = new FileReader("/sys/class/net/wlan0/address");
            } catch (FileNotFoundException e) {
                fstream = new FileReader("/sys/class/net/eth0/address");
            }
            BufferedReader in = null;
            if (fstream != null) {
                try {
                    in = new BufferedReader(fstream, 1024);
                    mac = in.readLine();
                } catch (IOException e) {
                } finally {
                    if (fstream != null) {
                        try {
                            fstream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            json.put("mac", mac);
            if (TextUtils.isEmpty(device_id)) {
                device_id = mac;
            }
            if (TextUtils.isEmpty(device_id)) {
                device_id = android.provider.Settings.Secure.getString(context.getContentResolver(),
                        android.provider.Settings.Secure.ANDROID_ID);
            }
            json.put("device_id", device_id);
            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

//    ==========================更新
private int PAGER_JSON=1;
    public void upData(){
        Log.i("mrl","进来了");
//      域名 139.129.19.190
        Request<JSONObject> request = NoHttp.createJsonObjectRequest(Const.WEB_BASE_URL+"User/getAppVersion", RequestMethod.GET);
        request.add("system",1);
        BeautyLiveApplication.getRequestQueue().add(PAGER_JSON, request, upDataOnResponse);
    }

    private OnResponseListener<JSONObject> upDataOnResponse = new OnResponseListener<JSONObject>() {
        @Override
        public void onStart(int i) {
            L.i("lll", "开始了");
        }

        @Override
        public void onSucceed(int i, Response<JSONObject> response) {
            if (i == PAGER_JSON) {// 判断what是否是刚才指定的请求
                //                {"code":0,"msg":"ok","data":"320200"}这个是什么
                // 请求成功
                JSONObject result = response.get();// 响应结果
//                Gson gson=new Gson();
//                UpDataBean upDataBean=gson.fromJson(result.toString(),UpDataBean.class);
//                isUpData(upDataBean);
                Log.i("mrl",result.toString());
                try {
                    JSONObject versiondata=result.getJSONObject("data");
                    String version=versiondata.getString("apkversion");
                    isUpData(version);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                // 响应头
                Headers headers = response.getHeaders();
                headers.getResponseCode();// 响应码
                response.getNetworkMillis();// 请求花费的时间
            }
        }

        @Override
        public void onFailed(int i, String s, Object o, Exception e, int i1, long l) {
            L.i("lll", "请求失败了哦" + s);
        }

        @Override
        public void onFinish(int i) {
            L.i("lll", "viewpager结束了");
        }
    };
    //  判断是否更新
    public void isUpData(UpDataBean updata){
        if (upDataState(Packages.getVersionName(getActivity()),updata.getVersion())<0){
            showUpDataDialog(updata);
        }
    }

    //  判断是否更新
    public void isUpData(String updata){
        if (upDataState(Packages.getVersionName(getActivity()),updata)<0){
            showUpDataDialog();
        }
    }

    public void showUpDataDialog(final UpDataBean updata){
        MessageDialog dialog = new MessageDialog(getActivity());
        dialog.setContent(R.string.mian_updata_tip);
        dialog.setMessageDialogListener(new MessageDialog.MessageDialogListener() {
            @Override
            public void onCancelClick(MessageDialog dialog) {
                dialog.dismiss();
            }

            @Override
            public void onCommitClick(MessageDialog dialog) {
                if (dialog!=null && dialog.isShowing()){
                    dialog.dismiss();
                }
//                进行下载
//                upapk(updata);
            }
        });
        dialog.show();
    }
    public void showUpDataDialog(){
        MessageDialog dialog = new MessageDialog(getActivity());
        dialog.setContent(R.string.mian_updata_tip);
        dialog.setMessageDialogListener(new MessageDialog.MessageDialogListener() {
            @Override
            public void onCancelClick(MessageDialog dialog) {
                dialog.dismiss();
            }

            @Override
            public void onCommitClick(MessageDialog dialog) {
                if (dialog!=null && dialog.isShowing()){
                    dialog.dismiss();
                }
//                进行下载
//                upapk(updata);
            }
        });
        dialog.show();
    }

    public void upapk( UpDataBean updata){
        IntentFilter filter=new IntentFilter();
        filter.addAction(DownLoadService.ACTION_UPDATA);
        filter.addAction(DownLoadService.ACTION_END);
        filter.addAction(DownLoadService.ACTION_START);
        getActivity().registerReceiver(broadcastReceiver,filter);
        Intent intent=new Intent(getActivity(),DownLoadService.class);
        intent.setAction(DownLoadService.ACTION_START);
        intent.putExtra("downLoadurl",updata.getUrl());
        intent.putExtra("appPath", Environment.getExternalStorageDirectory().getAbsolutePath());
//        Log.i("mrl",Environment.getExternalStorageDirectory().getAbsolutePath()+"/mrldownload/"+" zzzz");
        intent.putExtra("appName",getResources().getString(R.string.app_name));
        getActivity().startService(intent);
    }


    //安装apk
    protected void installApk(String path) {
        Log.i("mrl","这个是安装"+path);
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //执行的数据类型
        intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive");
        startActivity(intent);
    }

    //    更新进度条哦
    BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
//            更新进度
            if (intent.getAction()==DownLoadService.ACTION_END){
                installApk(Environment.getExternalStorageDirectory().getAbsolutePath()+getResources().getString(R.string.app_name));
            }
        }
    };

    /*
	 * 从服务器中下载APK
	 */
    protected void downLoadApk(final UpDataBean updata) {
        final ProgressDialog pd;    //进度条对话框
        pd = new  ProgressDialog(getActivity());
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载更新");
        pd.show();
        new Thread(){
            @Override
            public void run() {
                try {
                    File file = DownLoadUtil.getFileFromServer(updata.getUrl(),pd);
                    sleep(3000);
                    installApk(file);
                    pd.dismiss(); //结束掉进度条对话框
                } catch (Exception e) {
                    handler.sendEmptyMessage(5);
                    e.printStackTrace();
                }
            }}.start();
    }

    //安装apk
    protected void installApk(File file) {
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        //执行的数据类型
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }

    Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
//             *  开启直播验证
//             *
//             *  @param reponse  token  ucid
//             *
//             *  @return 服务器返回 data:( 0 ：可直播；1：未签约；2：时间不对;3:其他错误)
            switch (msg.what){
                case 5:
                    toastShort("下载失败");
                    break;
            }
        }
    };

    public int upDataState(String oldVersion,String newVersion){
//        old大于new则不进行更新  负数更新
        return oldVersion.compareTo(newVersion);
    }

    public HotAnchorPresenter getPresenter() {
        return presenter;
    }

   public void GoTop(){
       if (adapter!=null){
           LinearLayoutManager linearLayoutManager= (LinearLayoutManager) recyclerView.getLayoutManager();
           linearLayoutManager.scrollToPosition(0);
       }
   }
}
